package com.cloud.wms.ui.print.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;

import androidx.core.content.ContextCompat;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.cloud.wms.R;
import com.cloud.wms.app.FineExApplication;
import com.cloud.wms.base.BaseBarListActivity;
import com.cloud.wms.config.SpKey;
import com.cloud.wms.ui.print.contact.SelectBoxContact;
import com.cloud.wms.ui.print.presenter.SelectBoxPresenter;
import com.cloud.wms.widget.dialog.AlertDialogBuilder;
import com.inuker.bluetooth.library.BluetoothClient;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import butterknife.BindView;

/**
 * Created by FC on 2020/5/29.
 * Desc：
 */
public class BluetoothPrinterActivity extends BaseBarListActivity<BluetoothDevice, SelectBoxPresenter> implements SelectBoxContact.View {
    public static final int REQUEST_BLUETOOTH = 0x101;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    private BluetoothClient mClient;
    private SearchRequest request;

    @Override
    protected int getResId() {
        return R.layout.print_setting_activity;
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mClient = new BluetoothClient(this);
        request = new SearchRequest.Builder()
                .searchBluetoothLeDevice(3000, 2)   // 先扫BLE设备2次，每次3s
                .searchBluetoothClassicDevice(5000) // 再扫经典蓝牙5s
                .searchBluetoothLeDevice(2000)      // 再扫BLE设备2s
                .build();
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            mAdapter.getData().clear();
            mAdapter.notifyDataSetChanged();
            searchDevice();
        });
        if (!mClient.isBleSupported()) {
            info("该设备不支持蓝牙");
            return;
        }
        if (!mClient.isBluetoothOpened()) {
            new AlertDialogBuilder(this)
                    .setTitle("开启蓝牙")
                    .setMessage("使用该功能需要开启蓝牙，请确认开启")
                    .setPositiveButton("去开启", (dialog, which) -> {
                        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        BluetoothPrinterActivity.this.startActivityForResult(intent, REQUEST_BLUETOOTH);
                    })
                    .setNegativeButton("退出",  (dialog, which) -> BluetoothPrinterActivity.this.finish())
                    .show();
            return;
        }
        searchDevice();
    }

    @Override
    protected String barTitle() {
        return "打印机设置";
    }

    /**
     * 蓝牙搜索设备
     */
    private void searchDevice() {
        mClient.search(request, new SearchResponse() {
            @Override
            public void onSearchStarted() {

            }

            @Override
            public void onDeviceFounded(SearchResult result) {
                if (TextUtils.isEmpty(result.device.getName())) {
                    return;
                }
                if (mAdapter.getData().contains(result.device)) {
                    return;
                }
                mAdapter.addData(result.device);
            }

            @Override
            public void onSearchStopped() {
                refreshLayout.finishRefresh();
            }

            @Override
            public void onSearchCanceled() {

            }
        });
    }

    @Override
    public void onSuccess(Message message) {
        super.onSuccess(message);
    }

    /**
     * 保存连接蓝牙地址，名称
     *
     * @param bleDecvice
     */
    private void setBleDevice(BluetoothDevice bleDecvice) {
        FineExApplication.component().kv().encode(SpKey.PRINT_DEVICE, bleDecvice.getAddress());
        FineExApplication.component().kv().encode(SpKey.PRINT_DEVICE_NAME, bleDecvice.getName());
    }

    private void removeBleDevice() {
        FineExApplication.component().kv().removeValueForKey(SpKey.PRINT_DEVICE);
        FineExApplication.component().kv().removeValueForKey(SpKey.PRINT_DEVICE_NAME);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mClient.stopSearch();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void setupComponent() {
    }

    @Override
    protected int getItemResId() {
        return R.layout.print_device_item;
    }

    @Override
    protected void bindItemData(BaseViewHolder helper, BluetoothDevice item) {
        String macDevice = FineExApplication.component().kv().getString(SpKey.PRINT_DEVICE, "");
        helper.setText(R.id.tv_device_name, item.getName())
                .setText(R.id.tv_device_state, item.getAddress().equals(macDevice) ? "当前打印机" : "设置为打印机")
                .setTextColor(R.id.tv_device_state, ContextCompat.getColor(this, item.getAddress().equals(macDevice) ? R.color.btn_blue : R.color.font_black));
    }

    @Override
    protected void itemClickListener(BaseQuickAdapter<BluetoothDevice, BaseViewHolder> mAdapter, View view, int position) {
        super.itemClickListener(mAdapter, view, position);
        BluetoothDevice item = (BluetoothDevice) mAdapter.getItem(position);
        if (!mClient.isBluetoothOpened()) {
            info("蓝牙已关闭,请开启蓝牙");
            return;
        }
        if (item.getAddress().equals(FineExApplication.component().kv().getString(SpKey.PRINT_DEVICE, ""))) {
            success("取消设置成功");
            removeBleDevice();
        } else {//连接
            setBleDevice(item);
            success("设置成功");
            FineExApplication.component().printer().initPrinter(FineExApplication.component().kv().getString(SpKey.PRINT_DEVICE, ""));
        }
        mAdapter.notifyDataSetChanged();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_BLUETOOTH && resultCode == RESULT_OK) {
            success("开启蓝牙成功");
        }
    }
}